package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.MaoYanMovieBoxDetailModel;
import com.xiaotu.common.util.CacheHandler;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.HtmlUtil;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.PropertiesUtil;
import com.xiaotu.common.util.SepratorUtil;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.AUrlPageProcessor;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;

/**
 * @类名 MaoYanBoxOfficeDetailPageProcessor
 * @日期 2020年3月3日
 * @作者 wyl
 * @功能  票房明细
 */
@Component("MaoYanBoxOfficeDetailPageProcessor")
public class MaoYanBoxOfficeDetailPageProcessor extends AUrlPageProcessor {

	@Autowired
	private CacheHandler cacheHandler;
	
	private Map<String,String> cookies = new HashMap<String,String>();
	
	{
		cookies.put("Cookie", PropertiesUtil.getProperty("BoxOffice.site.Cookie"));
	}
	
    public static final String BOX_DETAIL_URL = "https://piaofang.maoyan.com/movie/%s/boxshow";//（票房明细）
    
    @Autowired
    private MaoYanMovieBasicInfoService maoYanMovieBasicInfoService;
    
	/*@SuppressWarnings("unchecked")
	@Override
	protected Request getStartRequest(JSONObject target) {
		Request request =null;
		try{
			request = new Request(String.format(BOX_DETAIL_URL, target.getString("dataid")));
			request.setExtras((Map<String, Object>)target);
		}catch (Exception e) {
			System.out.println(target.getString("dataId"));
		}
		return request;
	}*/
	
    
    @Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("/boxshow"))
        	return Constants.PageDataType.MOVIE_BOX_DETAIL;
        return Constants.PageDataType.SEARCH_LIST;
	}
    
	@Override
	public void process(Page page) {
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		switch (this.getPageDataType(page))
        {
	        case Constants.PageDataType.MOVIE_BOX_DETAIL:
	        	this.getMovieBoxDetail(page,extrasMap);
	        	break;
	        default:
                this.addRequestProcess(page);
                break;
        }
	}
	
	public void addRequestProcess(Page page){
		List<Map<String, Object>> movList = maoYanMovieBasicInfoService.queryMovieBoxOfficeList();
		movList.forEach(movMap ->
        {
            /*String dataId = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, StringUtil
                    .nullToString(movMap.get("dataid")));
            if (StringUtils.isEmpty(dataId))
                return;*/
            //Map<String, Object> paramMap = new HashMap<String, Object>();
            //paramMap.put("dataId", dataId);
            //paramMap.put("mvName", StringUtil.nullToString(movMap.get("mvName")));
        	String playDate = movMap.get("playDate")+"";
        	movMap.put("playDate", playDate);
            cacheHandler.hSet("MAOYAN_BOX_DETAIL_STORAGE", movMap
            		.get("dataid")+ SepratorUtil.SEP_UNDERLINE + movMap.get("playDate")+ SepratorUtil
                    .SEP_UNDERLINE + movMap.get("broadCastType")+"_"+ movMap.get("id"), movMap);
			//PageUtils.addTargetRequest(page, String.format(BOX_DETAIL_URL, dataId), paramMap);
        });
	}
	
	//电影票房明细
	private void getMovieBoxDetail(Page page, Map<String, Object> extrasMap) {
		String dataId = extrasMap.get("dataId").toString();
		String mvName = extrasMap.get("mvName").toString();
		String url = page.getRequest().getUrl();
		if(url.contains(dataId)){
			//解密加密数据
			Html html = PageUtils.spiderAudienceRating(page,cookies);
			List<String> dateList = html.xpath("//section[@class='table-wrapper']//div[@class='t-table-wrapper']"
					+ "//div[@class='t-table']//div[@class='t-row']//div[@class='t-col']//span").all();
			
			List<String> boxList = html.xpath("//section[@class='table-wrapper']//div[@class='t-other-col t-scroller']"
					+ "//div[@class='t-change-wrapper']//div[@class='t-change']//div[@class='t-row']").all();
			List<MaoYanMovieBoxDetailModel> maoYanMovieBoxDetailList = new ArrayList<MaoYanMovieBoxDetailModel>();
			if(dateList.size() == boxList.size() && dateList.size()>0 && boxList.size()>0){
				for(int i=0;i<dateList.size();i++){
					String str = HtmlUtil.delHTMLTag(dateList.get(i));
					String weekSplit = str.substring(str.indexOf("周"), str.indexOf("周")+2);
					String [] tempDateArr = HtmlUtil.delHTMLTag(dateList.get(i)).split(weekSplit);
					Html boxHtml = new Html(boxList.get(i));
					List<String> all = boxHtml.xpath("//div[@class='t-row']//div[@class='t-col']//i[@class='cs']//text()").all();
					if(null == tempDateArr || null==all || tempDateArr.length!=2 || all.size()!=17)
						throw new SpiderException(SpiderExceptionCode.DataInvalideException);
					MaoYanMovieBoxDetailModel maoYanMovieBoxDetailModel = new MaoYanMovieBoxDetailModel(
							null,mvName,dataId,null,
							tempDateArr[0],weekSplit,tempDateArr[1].trim(),
							all.get(0)+"万",all.get(1),all.get(2),all.get(3),
							all.get(4),all.get(5),all.get(6),all.get(7),
							all.get(8),all.get(9),all.get(10),all.get(11),
							all.get(12),all.get(13),all.get(14)+"万",all.get(15),
							all.get(16)
							);
					
					maoYanMovieBoxDetailList.add(maoYanMovieBoxDetailModel);
				}
				page.putField(MaoYanMovieBoxDetailModel.class.getName(), maoYanMovieBoxDetailList);
				//cacheHandler.hDel("MAOYAN_BOX_DETAIL_NEW", dataId+"_"+mvName);
			}
		}
		
	}

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}


	@Override
	protected String[] getStartRequestUrls() {
		return new String[]{"https://www.baidu.com/"};
	}

}